#coding=utf-8

import base64
import json
import datetime
import time
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from common.mymako import render_mako_context
from blueking.component.shortcuts import get_client_by_request, get_client_by_user
from django.template import RequestContext

from demo.models import History, Host, HostStat
from demo.tasks import *

import sys
reload(sys)
sys.setdefaultencoding("utf-8")
# Create your views here.
cmd = """
#!/bin/bash

MEMORY=$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2 }')
DISK=$(df -h | awk '$NF=="/"{printf "%s", $5}')
CPU=$(top -bn1 | grep load | awk '{printf "%.2f%%", $(NF-2)}')
DATE=$(date "+%Y-%m-%d %H:%M:%S")
echo -e "$DATE|$MEMORY|$DISK|$CPU"
"""


def home(request):
    bk_biz_id = request.POST.get("bk_biz_id")
    ip = request.POST.get("ip")

    client = get_client_by_request(request)
    res = client.cc.search_business()
    bizs = []
    if res["result"]:
        bizs = res["data"]["info"]

    if bk_biz_id is None:
        bk_biz_id = 2

    if ip is None:
        ip = ''

    ip_data = []

    if ip is not None and len(ip) > 0:
        ip_data.append(ip)

    args = {
        "bk_biz_id": bk_biz_id,
        "page": {
            "start": 0,
            "limit": 5,
            "sort": "bk_host_id"
        },
        "ip": {
            "data": ip_data,
            "exact": 1,
            "flag": "bk_host_innerip|bk_host_outerip"
        },
        "condition": [
            {
                "bk_obj_id": "host",
                "fields": [],
                "condition": []
            },
            {
                "bk_obj_id": "module",
                "fields": [],
                "condition": []
            },
            {
                "bk_obj_id": "set",
                "fields": [],
                "condition": []
            },
            {
                "bk_obj_id": "biz",
                "fields": [
                    "default",
                    "bk_biz_id",
                    "bk_biz_name"
                ],
                "condition": [
                    {
                        "field": "bk_biz_id",
                        "operator": "$eq",
                        "value": bk_biz_id
                    }
                ]
            }
        ]
    }

    hosts_res = client.cc.search_host(args)

    hosts = []
    if hosts_res["result"]:
        for info in hosts_res['data']["info"]:
            hosts.append(info["host"])
    return render_mako_context(request, "/demo/homepage.html", {"bizs": bizs, "hosts": hosts, "ip": ip, "bkBizId": bk_biz_id})


def check_host(request):

    bk_biz_id = request.POST.get("bk_biz_id")
    ip = request.POST.get("bk_host_innerip")

    content = base64.b64encode(cmd)
    ip_list = [{"ip": ip, "bk_cloud_id": 0}]

    args = {"bk_biz_id": bk_biz_id,
            "ip_list": ip_list,
            "account": "root",
            "script_content": content}
    client = get_client_by_user("admin")
    job_id = client.job.fast_execute_script(args)['data']['job_instance_id']

    status_args = {"bk_biz_id": bk_biz_id, "job_instance_id": job_id}
    while True:
        is_finished = client.job.get_job_instance_status(status_args)['data']['is_finished']
        if is_finished:
            break
        time.sleep(0.5)
    response = client.job.get_job_instance_log(status_args)

    history = History(ip=ip, user=request.user, action=u"立即检查")
    history.save()

    return JsonResponse(dict(message=u"巡检成功",
                             result=True,
                             data={'log': response['data'][0]['step_results'][0]['ip_logs'][0]['log_content'],
                                    'time': ("%s" % datetime.datetime.now())}))


def add_check_host(request):

    bk_biz_id = request.POST.get("bk_biz_id")
    ip = request.POST.get("bk_host_innerip")
    history = History(ip=ip, user=request.user, action=u"加入自动检查")
    history.save()

    hosts = Host.objects.filter(bk_biz_id=bk_biz_id, ip=ip)

    if len(hosts) == 0:
        host = Host(bk_biz_id=bk_biz_id, ip=ip)
        host.save()

    return JsonResponse(dict(message=u"加入自动检查", result=True))


def remove_check_host(request):

    bk_biz_id = request.POST.get("bk_biz_id")
    ip = request.POST.get("bk_host_innerip")

    history = History(ip=ip, user=request.user, action=u"取消自动检查")
    history.save()

    Host.objects.filter(bk_biz_id=bk_biz_id, ip=ip).delete()

    return JsonResponse(dict(message=u"取消自动检查", result=True))


def host(request):
    bk_biz_id = request.POST.get("bk_biz_id")
    ip = request.POST.get("ip")

    if bk_biz_id is None:
        bk_biz_id = 2

    if ip is None:
        ip = ''

    client = get_client_by_request(request)
    res = client.cc.search_business()
    bizs = []
    if res["result"]:
        bizs = res["data"]["info"]

    return render_mako_context(request, "/demo/host.html", {"bizs": bizs, "ip": ip, "bkBizId": bk_biz_id })


def get_host_stat(request):
    bk_biz_id = request.POST.get("bk_biz_id")
    ip = request.POST.get("ip")

    hosts = []

    if bk_biz_id is None:
        bk_biz_id = 2

    if ip is not None and len(ip) > 0:
        hosts = Host.objects.filter(bk_biz_id=bk_biz_id, ip=ip)
    else:
        hosts = Host.objects.filter(bk_biz_id=bk_biz_id)

    data = []
    for host in hosts:
        stat = {"ip": host.ip,
                "x_axis": [],
                "series": []
                }
        records = HostStat.objects.filter(bk_biz_id=bk_biz_id, ip=host.ip)[0:10]
        records = sorted(records, key=lambda record: record.id)
        cpus = []
        mems = []
        disks = []
        for record in records:
            stat["x_axis"].append(record.monitor_time.split()[1])
            cpus.append(record.cpu)
            mems.append(record.mem)
            disks.append(record.disk)
        stat["series"].append(dict(data=cpus, type="line", name="cpu"))
        stat["series"].append(dict(data=mems, type="line", name="mem"))
        stat["series"].append(dict(data=disks, type="line", name="disk"))
        data.append(stat)

    return JsonResponse(dict(message=u"success", result=True, data=data))


def history(request):
    histories = History.objects.all()
    return render_mako_context(request, "/demo/history.html", {'histories': histories})
